package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import util.HibernateUtil;
import view.LogonPage;
import bean.User;
import dto.LogonDTO;

public class LogonController {

	private LogonPage logon;
	private LogonDTO dto;

	public LogonDTO getDto() {
		return dto;
	}

	public void setDto(LogonDTO dto) {
		this.dto = dto;
	}

	void logon() {

		logon = new LogonPage();

		logon.addLogonListener(new LoginListener());
		logon.addClearListener();

		logon.setModal(true);
		logon.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		logon.setVisible(true);
	}

	private static int validateCredentials(LogonDTO dto) {

		int level = -1;
		User user = userLogin(dto);

		if (user != null) {
			level = user.getLevel();
		}

		return level;
	}

	private static User userLogin(LogonDTO dto) {
		// TODO password encyption
		String password = String.copyValueOf(dto.getPassword());

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

		Query query = session.createQuery(" FROM User WHERE USERID = '"
				+ dto.getUserName() + "' AND PASSWORD = '" + password + "'");

		User user = null;
		if (!query.list().isEmpty()) {
			user = (User) query.list().get(0);
		}

		return user;
	}

	class LoginListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			dto = logon.getDto();

			if (!dto.getUserName().equals("GUEST")) {
				dto.setLevel(LogonController.validateCredentials(dto));

				if (dto.getLevel() == -1) {
					logon.displayError("User unrecognized. Check your username and password.");
				} else {
					logon.dispose();
				}
			} else {
				logon.dispose();
			}
		}
	}

}
